﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RightControl.Common
{
    /// <summary>
    /// 常用公共类
    /// </summary>
    public class Common
    {
        #region 自动生成编号
        /// <summary>
        /// 表示全局唯一标识符 (GUID)。
        /// </summary>
        /// <returns></returns>
        public static string GuId()
        {
            return Guid.NewGuid().ToString();
        }
        /// <summary>
        /// 自动生成编号  201008251145409865
        /// </summary>
        /// <returns></returns>
        public static string CreateNo()
        {
            Random random = new Random();
            string strRandom = random.Next(1000, 10000).ToString(); //生成编号 
            string code = DateTime.Now.ToString("yyyyMMddHHmmss") + strRandom;//形如
            return code;
        }

        public static String RandomCode(int len = 6) {
            StringBuilder sb = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < len; i++) {
                sb.Append(random.Next(10));
            }
            return sb.ToString();
        }

        public static String RandomChar(int len = 2) {
            StringBuilder sb = new StringBuilder();
            String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            Random random = new Random();
            for (int i = 0; i < len; i++) {
                sb.Append(alpha[random.Next(35)]);
            }
            return sb.ToString();
        }
        #endregion
       

        /// <summary>
        /// 转16进制
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToHexString(byte[] bytes) {
            StringBuilder strB = new StringBuilder();
            if (bytes != null) {
                for (int i = 0; i < bytes.Length; i++) {
                    strB.Append(bytes[i].ToString("x2"));
                }
            }
            return strB.ToString();
        }


        public static String UrlEncode(String data, bool path) {
            StringBuilder encoded = new StringBuilder();
            String unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~" + (path ? "/" : "");

            foreach (char symbol in System.Text.Encoding.UTF8.GetBytes(data)) {
                if (unreservedChars.IndexOf(symbol) != -1) {
                    encoded.Append(symbol);
                }
                else {
                    encoded.Append("%" + String.Format("{0:X2}", (int)symbol));
                }
            } return encoded.ToString();
        }
    }
}
